package com.rainbow.support.seata.handler;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * seata的TCC模式,处理结果
 * @author 付为地
 */
public class TccResultHolder {

    private static final Map<Class<?>, Map<String, String>> cache = new ConcurrentHashMap<Class<?>, Map<String, String>>();

    /**
     * 存储tcc执行结果
     * @param actionClass 执行类
     * @param xid 事务xid
     * @param value 存储内容
     */
    public static void put(Class<?> actionClass, String xid, String value) {
        Map<String, String> result = cache.get(actionClass);
        if (ObjectUtils.isEmpty(result)) {
            synchronized (cache) {
                if (ObjectUtils.isEmpty(result)) {
                    result = new ConcurrentHashMap<>();
                    cache.put(actionClass, result);
                }
            }
        }
        result.put(xid, value);
    }

    /**
     * 获取tcc执行结果
     * @param actionClass 执行类
     * @param xid 事务xid
     * @return tcc执行结果
     */
    public static String get(Class<?> actionClass, String xid) {
        return MapUtils.getString(cache.get(actionClass),xid);
    }

    /**
     * 移除tcc执行结果
     * @param actionClass 执行类
     * @param xid 事务xid
     */
    public static void remove(Class<?> actionClass, String xid) {
        Map<String, String> result = cache.get(actionClass);
        if (ObjectUtils.isNotEmpty(result)) {
            result.remove(xid);
        }
    }
}
